﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class HashardAndContractsReport : Form
    {
        public HashardAndContractsReport()
        {
            InitializeComponent();
        }

        int regID, avpID, Year;

        int? regionID, avp_ID, Year_param;
        bool? hasOfice, HasOficeEqip, WaterPl, PlanLim;
        RESP_IIWaterAssessment.Entity.RESP_addDataContext resp_data = new RESP_IIWaterAssessment.Entity.RESP_addDataContext(DBClass.RESPContext.Connection);

        private void chbRegion_CheckedChanged(object sender, EventArgs e)
        {
            cbRegion.Enabled = chbRegion.Checked;
        }

        private void chbAVP_CheckedChanged(object sender, EventArgs e)
        {
            cbAVP.Enabled = chbAVP.Checked;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            numYear.Enabled = chbYear.Checked;
        }

        private void chbOfice_CheckedChanged(object sender, EventArgs e)
        {
            groupBox2.Enabled = chbOfice.Checked;
        }

        private void chbPlane_CheckedChanged(object sender, EventArgs e)
        {
            groupBox3.Enabled = chbPlane.Enabled;
        }

        private void HashardAndContractsReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                chbRegion.Checked = true;
                cbRegion.Enabled = chbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;

            }

            Year = (int)numYear.Value;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            regID = Convert.ToInt32(cbRegion.SelectedValue);
            chbAVP.Enabled = true;
            cbAVP.Text = string.Empty;
            //cbAVP.Items.Clear();
            cbAVP.DataSource = UtilClass.FillAVP(regID);
            cbAVP.DisplayMember = "Name";
            cbAVP.ValueMember = "ID";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
            }
        }

        private void numYear_ValueChanged(object sender, EventArgs e)
        {
            Year = (int)numYear.Value;
        }

        private void chbOfEqup_CheckedChanged(object sender, EventArgs e)
        {
            groupBox4.Enabled = chbOfEqup.Checked;
        }

        private void chbLimitPlane_CheckedChanged(object sender, EventArgs e)
        {
            groupBox5.Enabled = chbLimitPlane.Checked;
        }

        private void buttonShowReport_Click(object sender, EventArgs e)
        {
            if (chbRegion.Checked)
                regionID = regID;
            else
                regionID = null;

            if (chbAVP.Checked)
                avp_ID = avpID;
            else
                avp_ID = null;

            if (chbYear.Checked)
                Year_param = Year;
            else
                Year_param = null;

            if (chbOfice.Checked)
                hasOfice = rbOficeTrue.Checked;
            else
                hasOfice = null;

            if (chbOfEqup.Checked)
                HasOficeEqip = rbOfEqupTrue.Checked;
            else
                HasOficeEqip = null;

            if (chbPlane.Checked)
                WaterPl = rbPlaneTrue.Checked;
            else
                WaterPl = null;

            if (chbLimitPlane.Checked)
                PlanLim = rbLimitPlaneTrue.Checked;
            else
                PlanLim = null;

            dgvReportView.DataSource = resp_data.HasharsAndContractsAVP_n(avp_ID, regionID, Year_param, hasOfice, HasOficeEqip, WaterPl, PlanLim,
                                                                          InformationClass.Lang);
            GridSetting();
        }

        private void GridSetting()
        {
            if (InformationClass.Lang)
            {
                dgvReportView.Columns["RegName"].HeaderText = "Район";
                dgvReportView.Columns["AVPNAME"].HeaderText = "АВП";
                dgvReportView.Columns["Year"].HeaderText = "Год";
                dgvReportView.Columns["HasOffice"].HeaderText = "Наличие офиса";
                dgvReportView.Columns["HasEquipment"].HeaderText = "Оформление офиса";
                dgvReportView.Columns["UISContracts"].HeaderText = "договоров с УИС";
                dgvReportView.Columns["FHContracts"].HeaderText = "договоров с ФХ";
                dgvReportView.Columns["OtherContrats"].HeaderText = "договоров с Прочими";
                dgvReportView.Columns["OGMEContracts"].HeaderText = "договоров с ОГМЭ";
                dgvReportView.Columns["HasWateringPlan"].HeaderText = "План водопользования";
                dgvReportView.Columns["HasLimitPlan"].HeaderText = "План лимита";
                dgvReportView.Columns["HasWaterDemand"].HeaderText = "Наличие заявки на воду от водопотребителей";
                dgvReportView.Columns["HasUISJournal"].HeaderText = "Журнал УИС";
                dgvReportView.Columns["HasFlowJournal"].HeaderText = "Журнал водопот.";
                dgvReportView.Columns["hashcount"].HeaderText = "Кол-во хашаров";
                dgvReportView.Columns["hasharDays"].HeaderText = "Кол-во дней хашаров";
                dgvReportView.Columns["hasharPeopleCount"].HeaderText = "Кол-во человек задействованных в хашарах";
            }
            else
            {
                dgvReportView.Columns["RegName"].HeaderText = "Туман номи";
                dgvReportView.Columns["AVPNAME"].HeaderText = "СИУ номи";
                dgvReportView.Columns["Year"].HeaderText = "Йил";
                dgvReportView.Columns["HasOffice"].HeaderText = "Идора мавжудлиги";
                dgvReportView.Columns["HasEquipment"].HeaderText = "Идоранинг жиҳозланганлиги";
                dgvReportView.Columns["UISContracts"].HeaderText = "СИУ шартномалари сони ИТБ билан";
                dgvReportView.Columns["FHContracts"].HeaderText = "СИУ шартномалари сони фермерлар билан";
                dgvReportView.Columns["OtherContrats"].HeaderText = "СИУ шартномалари сони бошқалар билан";
                dgvReportView.Columns["OGMEContracts"].HeaderText = "СИУ шартномалари сони ВГМЭ билан";
                dgvReportView.Columns["HasWateringPlan"].HeaderText = "Режанинг мавжудлиги сув истеъмолчилари";
                dgvReportView.Columns["HasLimitPlan"].HeaderText = "Режанинг мавжудлиги лимит";
                dgvReportView.Columns["HasWaterDemand"].HeaderText = "Наличие заявки на воду от водопотребителей";
                dgvReportView.Columns["HasUISJournal"].HeaderText = "СИУ дан сув бериш-топшириш журнали ИТБ";
                dgvReportView.Columns["HasFlowJournal"].HeaderText = "СИУ дан сув бериш-топшириш журнали сув истеъмолчилари";
                dgvReportView.Columns["hashcount"].HeaderText = "Ҳашарлар сони";
                dgvReportView.Columns["hasharDays"].HeaderText = "Ҳашар кунлари сони";
                dgvReportView.Columns["hasharPeopleCount"].HeaderText = "Иштирок этган кишилар сони";
            }
        }

        private void dgvReportView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasOffice"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasEquipment"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasLimitPlan"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasUISJournal"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasWateringPlan"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["HasFlowJournal"]))
            {
                //if (dgvReportView["CheckRec"].FormattedValue == 0)
                //{
                    //if ((bool)e.Value)
                    //    e.Value = InformationClass.Lang ? "Да" : "Ха";
                    //else
                    //    e.Value = InformationClass.Lang ? "Нет" : "Йук";
                //}
            }

            if (e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["hashcount"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["hasharDays"]) ||
                e.ColumnIndex == dgvReportView.Columns.IndexOf(dgvReportView.Columns["hasharPeopleCount"]))
            {
                if (e.Value == null)
                    e.Value = 0;
            }

        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        //Workbooks excelappworkbooks;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvReportView.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
            }
            excelapp.Visible = true;
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i1r1.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i1r1uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";
            int left = 3, top = 10;

            if (chbRegion.Checked)
                excelworksheet.Cells[4, 3] = cbRegion.Text;

            if (chbYear.Checked)
                excelworksheet.Cells[5, 3] = (int)numYear.Value;

            //for (int i = 0; i < dgvReportView.Columns.Count; i++)
            //    excelworksheet.Cells[1, dgvReportView.Columns[i].DisplayIndex + 1] = dgvReportView.Columns[i].HeaderText.ToString();
            for (int i = 0; i < dgvReportView.Rows.Count; i++)
            {

                //excelworksheet.Cells[i + top, dgvReportView.Columns["RegName"].DisplayIndex + left] = dgvReportView["RegName", i].FormattedValue;
                //addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["RegName"].DisplayIndex + 3]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["AVPNAME"].DisplayIndex + 2] = dgvReportView["AVPNAME", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["AVPNAME"].DisplayIndex + 2]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasOffice"].DisplayIndex + 1] = dgvReportView["HasOffice", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasOffice"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasEquipment"].DisplayIndex + 1] = dgvReportView["HasEquipment", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasEquipment"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["UISContracts"].DisplayIndex + 1] = dgvReportView["UISContracts", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["UISContracts"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["FHContracts"].DisplayIndex + 1] = dgvReportView["FHContracts", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["FHContracts"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["OtherContrats"].DisplayIndex + 1] = dgvReportView["OtherContrats", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["OtherContrats"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["OGMEContracts"].DisplayIndex + 1] = dgvReportView["OGMEContracts", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["OGMEContracts"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasWateringPlan"].DisplayIndex + 1] = dgvReportView["HasWateringPlan", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasWateringPlan"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasLimitPlan"].DisplayIndex + 1] = dgvReportView["HasLimitPlan", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasLimitPlan"].DisplayIndex + 1]);
 
                excelworksheet.Cells[i + top, dgvReportView.Columns["HasWaterDemand"].DisplayIndex + 1] = dgvReportView["HasLimitPlan", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasWaterDemand"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasUISJournal"].DisplayIndex + 1] = dgvReportView["HasUISJournal", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasUISJournal"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["HasFlowJournal"].DisplayIndex + 1] = dgvReportView["HasFlowJournal", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["HasFlowJournal"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["hashcount"].DisplayIndex + 1] = dgvReportView["hashcount", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["hashcount"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["hasharDays"].DisplayIndex + 1] = dgvReportView["hasharDays", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["hasharDays"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, dgvReportView.Columns["hasharPeopleCount"].DisplayIndex + 1] = dgvReportView["hasharPeopleCount", i].FormattedValue;
                addBorder(excelworksheet.Cells[i + top, dgvReportView.Columns["hasharPeopleCount"].DisplayIndex + 1]);

                excelworksheet.Cells[i + top, 2] = i + 1;
                excelworksheet.get_Range(excelworksheet.Cells[i + 9, 2], excelworksheet.Cells[i + 9, 2]).Borders[XlBordersIndex.xlEdgeLeft].LineStyle = 1;
                excelworksheet.get_Range(excelworksheet.Cells[i + 9, 2], excelworksheet.Cells[i + 9, 2]).Borders[XlBordersIndex.xlEdgeBottom].LineStyle = 1;
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
            excelworksheet.Select(1);
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvReportView.RowCount > 0)
            {
                //GetReport();
                //excelworksheet.PrintPreview(Type.Missing);
                //excelworksheet.PrintOut(1, 1, 1, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                PrintDGV.Print_DataGridView(dgvReportView);
            }
        }

    }
}
